<template>
	<view class="userinfo">
		<view class="title" :style="{fontWeight:'bold',marginTop:'10rpx'}">
			个人资料:
		</view>
		<view class="avatar">
			<!-- TODO修改用户头像 -->
			<image
				src="../../static/avatar.png"
				style="width: 180rpx;height: 180rpx;margin-top: 20rpx;"></image>
			<view class="avatarRight">
				<text class="avatarTitle">修改头像</text>
				<u-upload   :fileList="fileListTest" accept="image" uploadText="点击上传" previewImage @delete="deletePic" @afterRead="afterRead" name="Test"></u-upload>
			</view>
		</view>

		<!-- TODO 用户信息页 -->
		<u--form :model="user" ref="uForm" :rules="rules" labelPosition="top" :labelStyle="{marginBottom:'20rpx'}"
			labelWidth="auto">
			<!-- 输入姓名 -->
			<u-form-item prop="username" label="姓名">
				<u--input v-model="user.username" placeholder="请输入姓名" border="surround" clearable></u--input>
			</u-form-item>
			<!--  电话号码-->
			<u-form-item prop="phoneNumber" label="电话号码">
				<u--input v-model="user.phoneNumber" placeholder="请输入电话号码" border="surround" clearable></u--input>
			</u-form-item>
			<!-- 现居地址 -->
			<u-form-item prop="address" label="现居地址">
				<u--input v-model="user.address" placeholder="请输入现居地址" border="surround" clearable></u--input>
			</u-form-item>
			<!--  门牌号-->
			<u-form-item prop="houseNumber" label="门牌号">
				<u--input v-model="user.houseNumber" placeholder="请输入门牌号" border="surround" clearable></u--input>
			</u-form-item>
			<!-- 身份证号 -->
			<u-form-item prop="idNumber" label="身份证号">
				<u--input v-model="user.idNumber" placeholder="请输入身份证号" border="surround" clearable></u--input>
			</u-form-item>

			<!-- <u-button @click="submit" type="primary" text="提交"></u-button> -->
		</u--form>
		<view class="btn" @click="submit">修改</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				user: {
					//去敏： 少定义一些敏感属性[status,password等]，重新封装 到达去敏效果！！！
					phoneNumber: "",
					username: "",
					address: "",
					idNumber: "",
					houseNumber: "",
					id: 0,
					password: "",
					status: 0,
				},
				rules: {
					'username': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						// 不希望表单重置后还有提示，去掉change
						trigger: ['blur']
					},
					'phoneNumber': {
						type: 'string',
						required: true,
						message: '请填写电话号码',
						trigger: ['blur']
					},
					'address': {
						type: 'string',
						required: true,
						message: '请填写现居地址',
						trigger: ['blur']
					},
					'houseNumber': {
						type: 'string',
						required: true,
						message: '请填写门牌号',
						trigger: ['blur']
					},
					'idNumber': {
						type: 'string',
						required: true,
						message: '请填写身份证号',
						trigger: ['blur']
					},
				},
				// !!name 根据你的fileList（数组）的名字来取，你是fileList1 name="1" fileListTest name="test"
				// this[`fileList${event.name}`].length 以及下面一些地方用了字符串的拼接而已
				fileListTest: [],
			}
		},
		methods: {
			// 1.根据id获取用户信息的方法
			getUserById() {
				let id = uni.getStorageSync('id')
				if (id) {
					uni.request({
						url: `http://blog.coldworld.top:8081/user/getuser/${id}`,
						method: "GET",
						// data:
						success: (res) => {
							if (res.data.code == 20000) {
								this.user = res.data.data.data
							}
						}
					})
				}
			},
			// 2.修改提交按钮 校验表单是否为空
			submit() {
				// 1.ref 配合 2.this.$refs.xx.....检验表单是否填写完 2.validateField()对某个字段校验 3.validate()校验所有字段
				this.$refs.uForm.validate().then(res => {
					// uni.$u.toast('校验通过')
					this.changeUserInfo()

				}).catch(errors => {

					// uni.$u.toast('请完整填写所有内容')
					uni.showToast({
						icon: 'error',
						title: '请完整填写所有内容',

					})
				})
			},
			// 3.发起请求 提交用户修改后信息的方法
			changeUserInfo() {
				uni.request({
					url: "http://blog.coldworld.top:8081/user/update",
					method: "PUT",
					data: this.user,
					success: (res) => {
						// console.log(res)
						let msg = res.data.message
						if (res.data.code == 20000) {
							uni.$u.toast(msg)
							setTimeout(() => {
								// 1.5s后跳到到我的
								uni.switchTab({
									url: '../my/my'
								})
							}, 1500)
							// 清空表单
							this.$refs.uForm.resetFields()
						} else {
							uni.showToast({
								title: "请先登录",
								icon: "error",
							})
							setTimeout(() => {
								// 1.5s后跳到到登录页
								uni.redirectTo({
									url: '../login/login'
								})
							}, 1500)
							// 清空表单
							this.$refs.uForm.resetFields()
						}
					}
				})
			},
			// 4.删除图片的方法
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 5.新增图片的方法
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			// 6.上传发送promise请求的方法
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://192.168.2.21:8081/upload', // TODO：后端提供上传接口
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
		},
		onLoad() {
			this.getUserById()

		},
		onShow() {
			this.getUserById()
		}

	}
</script>

<style lang="scss">
	.userinfo {
		padding: 20rpx;

		.btn {
			height: 100rpx;
			border-radius: 10rpx;
			background-color: #1269db;
			color: #fff;
			text-align: center;
			line-height: 80rpx;
			margin-top: 20rpx;
		}

		.avatar {
			display: flex;
			align-items: center;

			.avatarRight {
				margin-left: 50rpx;

				.avatarTitle {
					font-size: 10rpx;
				}
			}
		}

	}
</style>
